package com.xzxy.xmlg_backend.aspect;

/**
 * @Author: zys
 * @CreateTime: 2025-06-13
 */

import com.xzxy.xmlg_backend.entity.OperationLog;
import com.xzxy.xmlg_backend.mapper.OperationLogMapper;
import com.xzxy.xmlg_backend.utils.JwtUtils;
import com.xzxy.xmlg_backend.utils.ServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

@Aspect
@Component
public class OperationLogAspect {

    private final OperationLogMapper logMapper;

    public OperationLogAspect(OperationLogMapper logMapper) {
        this.logMapper = logMapper;
    }

    /**
     * 使用aop进行日志插入
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    // 定义切点：拦截所有 Controller 的方法
    @Around("execution(* com.xzxy.xmlg_backend.controller.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 提取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 2. 执行目标方法（继续流程）
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long spendTime = System.currentTimeMillis() - startTime;

        // 3. 封装日志数据
        OperationLog log = new OperationLog();
        String username = null;
        try {
            username = String.valueOf(JwtUtils.parseJWT(String.valueOf(request.getHeader("token"))).get("username"));
        }catch (Exception e){
            username = "用户未登录";
        }
        log.setUserName(username); // 实际可从登录态获取（如 SecurityContext）
        log.setOperationType(request.getRequestURI());
        log.setOperationMethod(request.getMethod());
        log.setRequestUrl(request.getRequestURL().toString());
        log.setOperationIp(ServletUtil.getClientIP(request)); // 工具类获取IP（需引入 Hutool 或手动实现）
        log.setOperationStatus("成功"); // 可根据 result 或异常处理状态
        log.setLastOperationTime(LocalDateTime.now());

        // 4. 写入数据库
        logMapper.insert(log);

        return result;
    }
}
